package com.emmmya.ocs.common.base;

import com.emmmya.ocs.common.utils.ResultUtil;
import com.emmmya.ocs.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;
import java.util.List;

/**
 *
 * @author: 咕噜肉IT小店-黑医
 * @createDate: 2022-05-17
 * @version: 1.0
 */
public abstract class BaseController<E, ID extends Serializable> {

    /**
     * 获取service
     * @return
     */
    @Autowired
    public abstract BaseService<E,ID> getService();

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result<E> get(@PathVariable ID id){

        E entity = getService().get(id);
        return new ResultUtil<E>().setData(entity);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<E>> getAll(){

        List<E> list = getService().getAll();
        return new ResultUtil<List<E>>().setData(list);
    }


    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result<E> save(E entity){

        try {
            E e = getService().save(entity);
            return new ResultUtil<E>().setData(e);
        } catch (Exception exception) {
            //exception.printStackTrace();
            return ResultUtil.error(exception);
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @ResponseBody
    //更新数据
    public Result<E> update(E entity){

        try {
            E e = getService().update(entity);
            return new ResultUtil<E>().setData(e);
        } catch (Exception exception) {
            //exception.printStackTrace();
            return ResultUtil.error(exception);
        }
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    //批量通过id删除
    public Result<Object> delAllByIds(@PathVariable ID[] ids){

        for(ID id:ids){
            getService().delete(id);
        }
        return ResultUtil.success("批量通过id删除数据成功");
    }
}
